package pnu.ssm.sbmother;

import pnu.ssm.http.HttpConnectorParent;
import pnu.ssm.key.SBString;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterActivity extends Activity {
	
	TextView tv_id;
	TextView tv_password;
	EditText et_id;
	EditText et_password;
	TextView tv_phone;
	EditText et_phone;
	Button btn_register;
	
	private HttpConnectorParent connector;
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_register_activty);
		buildUI();
	}
	
	private void buildUI(){
		dialog = new ProgressDialog(this);
		dialog.setMessage(SBString.WAIT);
		dialog.setIndeterminate(true);
		dialog.setCancelable(false);
		
		tv_id = (TextView) findViewById(R.id.tv_register_id);
		tv_password = (TextView) findViewById(R.id.tv_register_password);
		tv_phone = (TextView) findViewById(R.id.tv_register_phone);
		et_id = (EditText) findViewById(R.id.et_register_id);
		et_password = (EditText) findViewById(R.id.et_register_password);
		et_phone = (EditText) findViewById(R.id.et_register_phone);
		btn_register = (Button) findViewById(R.id.btn_register_web);
		connector = HttpConnectorParent.getInstance();
		
		
		btn_register.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				new RegisterAsynTask(et_id.getText().toString(), et_password.getText().toString(), 
						et_phone.getText().toString()).execute(null,null,null);
			}
		});
	}
	
	class RegisterAsynTask extends AsyncTask<Void, Void, String> {

		private String id;
		private String password;
		private String phoneNumber;

		public RegisterAsynTask(String id, String password, String phoneNumber) {
			this.id = id;
			this.password = password;
			this.phoneNumber = phoneNumber;
		}
		
		@Override
		protected void onPreExecute() {
			dialog.show();
			super.onPreExecute();
		}
		
		@Override
		protected String doInBackground(Void... params) {
			//parent_num를 반환해준다.
			String result = connector.register(id, password, phoneNumber);
			return result;
		}
		
		@Override
		protected void onPostExecute(String result) {
			dialog.dismiss();
			super.onPostExecute(result);
			if(result == null){
				Toast.makeText(RegisterActivity.this, "죄송합니다. 현재 서버 점검 중입니다. 조금 뒤 다시 시도해 주세요.", Toast.LENGTH_LONG).show();
			}else if(result.equalsIgnoreCase("success")){
				Toast.makeText(RegisterActivity.this, "가입되었습니다.", Toast.LENGTH_LONG).show();
				finish();
			}else{
				Toast.makeText(RegisterActivity.this, "가입에 실패하였습니다. 아이디가 중복되었거나 비밀번호를 확인해주세요.", Toast.LENGTH_LONG).show();
			}
		}
	}
}
